package com.zx.onlineeducation.service.edu.controller;


import com.zx.onlineeducation.common.util.R;
import com.zx.onlineeducation.service.edu.client.VodClient;
import com.zx.onlineeducation.service.edu.entity.VideoDO;
import com.zx.onlineeducation.service.edu.service.VideoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author 郑雪
 * @since 2022-01-13
 */
@Api(tags = "课程视频管理")
@RestController
@RequestMapping("/edu/video")
@CrossOrigin // 解决跨域
public class VideoController {

    /**
     * 课程视频服务接口
     */
    @Autowired
    private VideoService videoService;

    /**
     * VOD视频点播服务 远程接口
     */
    @Autowired
    private VodClient vodClient;

    @ApiOperation("添加课程视频")
    @PostMapping("/save")
    public R save(
            @ApiParam(value = "课程视频数据对象")
            @RequestBody VideoDO videoDO) {
        boolean save = videoService.save(videoDO);
        return save ? R.ok() : R.error();
    }

    @ApiOperation("根据ID查询课程视频")
    @GetMapping("/{id}")
    public R getById(
            @ApiParam(value = "课程视频ID", required = true)
            @PathVariable("id") String id) {
        VideoDO videoDO = videoService.getById(id);
        return R.ok().data("video", videoDO);
    }

    @ApiOperation("修改课程视频")
    @PutMapping("/{id}")
    public R update(
            @ApiParam(value = "课程视频ID", required = true)
            @PathVariable("id") String id,
            @ApiParam(value = "课程视频数据对象")
            @RequestBody VideoDO videoDO) {
        videoDO.setId(id);
        boolean update = videoService.updateById(videoDO);
        return update ? R.ok() : R.error();
    }

    @ApiOperation("逻辑删除课程视频")
    @DeleteMapping("/{id}")
    public R remove(
            @ApiParam(value = "课程视频ID", required = true)
            @PathVariable("id") String id) {
        // 根据ID获取课程视频数据对象
        VideoDO videoDO = videoService.getById(id);
        // 获取云端视频资源ID
        String videoSourceId = videoDO.getVideoSourceId();
        // 如果云端视频资源ID不为空，删除云端视频资源文件
        if (!StringUtils.isEmpty(videoSourceId)) {
            // 调用远程接口删除云端视频资源文件
            R removeVodFileResult = vodClient.removeVodFile(videoSourceId);
            // 如果删除云端视频失败
            if (!removeVodFileResult.getSuccess()) {
                // 返回失败
                return removeVodFileResult;
            }
        }
        // 如果删除云端视频资源文件成功，删除课程视频数据对象
        boolean remove = videoService.removeById(id);
        // 返回结果
        return remove ? R.ok() : R.error();
    }
}

